<template>
  <div>
    <UiBreadcrumbs
      :items="breadcrumbs"
      class="_breadcrumbs _container"
    />
    <ViewVideos
      v-if="data"
      :data="data"
      :status="status"
      hide-categories
      :title="h1"
      :data-models="modelsByTag"
      :top-random-categories="topRandomCategories"
    />
    <div
      v-else
      class="_loading"
    />
  </div>
</template>

<script setup lang="ts">
import type { IBreadcrumbItem } from '../../types';
import { convertQueryCategories, convertString } from '../../runtime';
import { VideosApiService } from '../../services/api/videos.service';
import { ModelsApiService } from '../../services/api/models.service';
import { CategoriesApiService } from '../../services/api/categories.service';
import { sortItemsDefault } from '../../lib';

const { t } = useI18n();

const pageName = useGetPureRouteName();

const [
  { data, status },
  { topRandomCategories },
  { data: modelsByTag },
] = await Promise.all([
  useFetchVideosByTag(VideosApiService.getListByNicheAndTag),
  useFetchTopRandomCategories(CategoriesApiService.getTopRandom, String(pageName)),
  useFetchModelsByTag(ModelsApiService.getListByTag, 100),
]);

useNoindexThinListing(() => data.value?.items?.length);

const route = useRoute();
const slug = computed(() => String(route.params[ 'tag' ]));

const title = convertString().fromSlug(slug.value);
const metaTitle = computed(() => convertString().toCapitalize(title));

const routeQueryCategories = computed(() => {
  if (route.query[ 'categories' ]) {
    const text = convertQueryCategories(route);
    return ` ${convertString().toCapitalize(text)}`;
  }
  return '';
});

const { meta, h1 } = useMeta({
  t,
  pageKey: pageName,
  brandName: useAppConfig().brandName,
  sortOptions: sortItemsDefault,
  text: metaTitle,
  secondText: routeQueryCategories,
});

watchEffect(() => {
  if (slug.value) {
    useHead(meta.value);
  }

  if ((status.value === 'error' || status.value === 'success') && (!data.value?.items?.length)) {
    throw createError({ statusCode: 404, statusMessage: 'Not Found' });
  }
});

const breadcrumbs = [
  {
    name: t('navigation.main'),
    to: '/',
  },
  {
    name: metaTitle.value,
  },
] as IBreadcrumbItem[];
</script>
